<template>
  <div class="container mx-auto px-4 py-8">
    <div class="flex justify-between items-center mb-8">
      <h1 class="text-3xl font-bold text-gray-800">文章管理</h1>
      <button
        @click="showCreateModal = true"
        class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors"
      >
        新建文章
      </button>
    </div>

    <table class="w-full bg-white rounded-lg shadow-md">
      <thead class="bg-gray-50">
        <tr>
          <th class="px-6 py-3 text-left text-sm font-medium text-gray-500">标题</th>
          <th class="px-6 py-3 text-left text-sm font-medium text-gray-500">作者</th>
          <th class="px-6 py-3 text-left text-sm font-medium text-gray-500">发布时间</th>
          <th class="px-6 py-3 text-left text-sm font-medium text-gray-500">操作</th>
        </tr>
      </thead>
      <tbody class="divide-y divide-gray-200">
        <tr v-for="post in posts" :key="post.id">
          <td class="px-6 py-4 text-sm text-gray-800">{{ post.title }}</td>
          <td class="px-6 py-4 text-sm text-gray-500">{{ post.author }}</td>
          <td class="px-6 py-4 text-sm text-gray-500">{{ post.created_at }}</td>
          <td class="px-6 py-4 text-sm space-x-4">
            <button @click="editPost(post)" class="text-blue-500 hover:text-blue-600">编辑</button>
            <button @click="deletePost(post.id)" class="text-red-500 hover:text-red-600">删除</button>
          </td>
        </tr>
      </tbody>
    </table>

    <!-- 新建/编辑模态框 -->
    <div v-if="showCreateModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center">
      <div class="bg-white rounded-lg p-6 w-full max-w-2xl">
        <h2 class="text-2xl font-bold mb-4">{{ editingPost ? '编辑文章' : '新建文章' }}</h2>
        <form @submit.prevent="submitForm">
          <div class="space-y-4">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">标题</label>
              <input
                v-model="formData.title"
                type="text"
                class="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                required
              >
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">摘要</label>
              <textarea
                v-model="formData.excerpt"
                rows="2"
                class="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              ></textarea>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">内容</label>
              <textarea
                v-model="formData.content"
                rows="4"
                class="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                required
              ></textarea>
            </div>
            <div class="flex justify-end space-x-4">
              <button
                type="button"
                @click="cancelEdit"
                class="px-4 py-2 border rounded-lg hover:bg-gray-50"
              >
                取消
              </button>
              <button
                type="submit"
                class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600"
              >
                {{ editingPost ? '保存修改' : '创建文章' }}
              </button>
            </div>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'

const posts = ref([])
const showCreateModal = ref(false)
const editingPost = ref(null)
const formData = ref({
  title: '',
  excerpt: '',
  content: '',
  author: '管理员'
})

const fetchPosts = async () => {
  try {
    const response = await axios.get('/api/admin/posts')
    posts.value = response.data
  } catch (error) {
    console.error('获取文章列表失败:', error)
  }
}

const editPost = (post) => {
  editingPost.value = post
  formData.value = { ...post }
  showCreateModal.value = true
}

const deletePost = async (id) => {
  if (!confirm('确定要删除这篇文章吗？')) return
  try {
    await axios.delete(`/api/admin/posts/${id}`)
    await fetchPosts()
  } catch (error) {
    console.error('删除文章失败:', error)
  }
}

const submitForm = async () => {
  try {
    if (editingPost.value) {
      await axios.put(`/api/admin/posts/${editingPost.value.id}`, formData.value)
    } else {
      const response = await axios.post('/api.php?c=BlogPost&a=createPost', {
        title: newPost.value.title,
        content: newPost.value.content,
        userID: currentUser.value.id
      })
    }
    showCreateModal.value = false
    await fetchPosts()
  } catch (error) {
    console.error('提交表单失败:', error)
  }
}

const cancelEdit = () => {
  showCreateModal.value = false
  editingPost.value = null
  formData.value = {
    title: '',
    excerpt: '',
    content: '',
    author: '管理员'
  }
}

onMounted(() => {
  fetchPosts()
})
</script>